/**
 * 
 */
package demo.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author roger.xu
 * 
 */
public class DateTimeUtils {

    private static final Log _log = LogFactory.getLog(DateTimeUtils.class.getSimpleName());

    /**
     * Parse the given ISO8601 formatted date string to produce a date.
     * 
     * @param str
     *            the string to be parsed. It should be formatted like "2010-02-03".
     * @return a Date parsed from the string.
     */
    public static Date parseISODate(final String str) {
        Date date = null;

        if (str == null) {
            return date;
        }

        final String pattern = DateFormatUtils.ISO_DATE_FORMAT.getPattern();
        final DateFormat formatter = new SimpleDateFormat(pattern);
        //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            date = formatter.parse(str);
        } catch (ParseException e) {
            _log.error(e.toString());
        }

        return date;
    }

    /**
     * Parse the given ISO8601 formatted date time string to produce a timestamp without timezone.
     * 
     * @param str
     *            the string to be parsed. It should be formatted like "2010-02-03T09:26:31".
     * @return a Date parsed from the string.
     */
    public static Date parseISODateTime(final String str) {
        Date date = null;

        if (str == null) {
            return date;
        }

        final String pattern = DateFormatUtils.ISO_DATETIME_FORMAT.getPattern();
        final DateFormat formatter = new SimpleDateFormat(pattern);
        //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            date = formatter.parse(str);
        } catch (ParseException e) {
            _log.error(e.toString());
        }

        return date;
    }

    /**
     * Parse the given ISO8601 formatted date time string to produce a timestamp.
     * 
     * @param str
     *            the string to be parsed. It should be formatted like "2010-02-03T09:26:31+08:00".
     * @return a Date parsed from the string.
     */
    public static Date parseISOTimestamp(final String str) {
        Date date = null;

        if (str == null) {
            return date;
        }

        final String pattern = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern();
        try {
            date = DateUtils.parseDate(str, new String[] { pattern });
        } catch (ParseException e) {
            _log.error(e.toString());
        }

        return date;
    }
}
